package com.tjrac.generalpermissions.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.tjrac.filter.entity.Verification;
import com.tjrac.filter.epception.PermissionDeniedException;
import com.tjrac.generalpermissions.domain.*;
import com.tjrac.generalpermissions.epception.MsgException;
import com.tjrac.generalpermissions.epception.statusCode.*;
import com.tjrac.generalpermissions.service.*;
import com.tjrac.generalpermissions.utils.MD5;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZeNing
 * @create 2020-11-30 22:46
 */
@RestController
@RequestMapping(value = "/manage")
public class ManageServlet {

    @Resource
    PermissionService permissionService;

    @Resource
    RoleService roleService;

    @Resource
    PTypeService pTypeService;

    @Resource
    RolePermissionService rolePermissionService;

    @Resource
    UserManagementService userManagementService;

    /**
     * 查询单个权限
     */
    @RequestMapping(value = "selectPermission", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectPermission(
            Integer id
    ) {
        try {
            return new MsgException(PermissionCode.SUCCESS_PERMISSION, "查询权限成功").toOneJson(permissionService.queryById(id));
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {
                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询所有权限
     */
    @RequestMapping(value = "selectAllPermission", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectAllPermission() {
        try {
            return permissionService.queryAllPermission();
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 添加权限
     */
    @RequestMapping(value = "addPermission", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String addPermission(
            String pName,
            String desc,
            String link,
            Integer ptid
    ) {
        Permission permission = new Permission(pName, desc, link, ptid);
        try {
            return permissionService.addPermission(permission);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 删除权限
     */
    @RequestMapping(value = "delPermission", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String delPermission(
            Integer id
    ) {
        try {

            //删除权限的同时,将权限角色映射表中该拥有该权限的行全部删除
            List<RolePermission> rolePermissions = rolePermissionService.queryRolePermissionByPid(id);
            if (rolePermissions != null) {
                for (RolePermission rp : rolePermissions) {
                    rolePermissionService.delRP(rp.getId());
                }
            }

            return permissionService.delPermission(id);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 修改权限
     */
    @RequestMapping(value = "modifyPermission", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String modifyPermission(
            Integer pid,
            String pName,
            String desc,
            String link,
            Integer ptid
    ) {
        Permission permission = new Permission(pid, pName, desc, link, ptid);
        try {
            return permissionService.modifyPermission(permission);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询单个角色
     */
    @RequestMapping(value = "selectRole", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectRole(
            Integer id
    ) {
        try {
            return new MsgException(RoleCode.SUCCESS_ROLE, "查询成功").toOneJson(roleService.queryById(id));
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询所有角色
     */
    @RequestMapping(value = "selectAllRole", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectAllRole() {
        try {
            return roleService.queryAllRole();
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 添加角色
     */
    @RequestMapping(value = "addRole", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String addRole(
            String rName,
            String desc
    ) {
        Role role = new Role(rName, desc, null);
        try {
            return roleService.addRole(role);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 删除角色
     */
    @RequestMapping(value = "delRole", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String delRole(
            Integer id
    ) {
        try {

            return roleService.delRole(id);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    @RequestMapping(value = "modifyRole", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String modifyRole(@RequestBody String jsonString) {
        JSONObject jsonObject = JSON.parseObject(jsonString);
        JSONArray array = (JSONArray) jsonObject.get("permissions");
        Object[] objects = array.toArray();
        Integer[] permissions = new Integer[objects.length];
        for (int i = 0; i < objects.length; i++) {
            permissions[i] = (int) objects[i];
        }
        return this.modifyRole(jsonObject.getInteger("id"),
                jsonObject.getString("rName"),
                jsonObject.getString("desc"),
                permissions);
    }

    /**
     * 修改角色
     */
    String modifyRole(
            Integer id,
            String rName,
            String desc,
            Integer[] permissions
    ) {
        Role role = new Role(id, rName, desc, null);
        try {
            return roleService.modifyRole(role, permissions);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }

 /*       //删除角色的同时,将权限角色映射表中该拥有该角色的行全部删除
        List<RolePermission> rolePermissions = null;
        try {
            rolePermissions = rolePermissionService.queryRolePermissionByRid(id);
        } catch (MsgException e) {
            return e.toJson();
        }
        if (rolePermissions != null) {
            for (RolePermission rp : rolePermissions) {
                try {
                    rolePermissionService.delRP(rp.getId());
                } catch (MsgException e) {
                    return e.toJson();
                }
            }
        }

        ArrayList<Verification> addPermissions = new ArrayList<>();
        for (Integer integer : permissions) {
            try {
                Permission permission = permissionService.queryById(integer);
                addPermissions.add(permission);
            } catch (MsgException e) {
                return e.toJson();
            }
        }

        Role role = new Role(id, rName, desc, addPermissions);

        try {

            //添加角色,同时添加权限角色映射表
            for (Integer integer : permissions) {
                try {
                    Permission permission = permissionService.queryById(integer);
                    rolePermissionService.addRP(new RolePermission(role, permission));
                } catch (MsgException e) {
                    return e.toJson();
                } catch (Exception e) {
                    e.printStackTrace();
                    return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
                }
            }

            return roleService.modifyRole(role);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {
                
                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }*/
    }

    /**
     * 查询单个权限类型
     */
    @RequestMapping(value = "selectPType", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectPType(
            Integer id
    ) {
        try {
            return new MsgException(PTypeCode.SUCCESS_PERMISSION_TYPE, "查询成功").toOneJson(pTypeService.queryById(id));
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询所有权限类型
     */
    @RequestMapping(value = "selectAllPType", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectAllPType() {
        try {
            return pTypeService.queryAllPType();
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 添加权限类型
     */
    @RequestMapping(value = "addPType", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String addPType(
            String ptName,
            String desc
    ) {
        PType pType = new PType(ptName, desc, null);
        try {
            return pTypeService.addPType(pType);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 删除权限类型
     */
    @RequestMapping(value = "delPType", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String delPType(
            Integer id
    ) {
        try {
            return pTypeService.delPType(id);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 修改权限类型
     */
    @RequestMapping(value = "modifyPType", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String modifyPType(
            Integer id,
            String ptName,
            String desc
    ) {
        PType pType = new PType(id, ptName, desc, null);
        try {
            return pTypeService.modifyPType(pType);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询单个用户
     */
    @RequestMapping(value = "selectUser", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectUser(
            Integer id
    ) {
        try {
            return new MsgException(UserManagementCode.SUCCESS_USER, "查询该用户成功").toOneJson(userManagementService.queryById(id));
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询单个用户
     */
    @RequestMapping(value = "selectUserByUsername", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectUserByUsername(
            String username
    ) {
        try {
            return new MsgException(UserManagementCode.SUCCESS_USER, "查询该用户成功").toOneJson(userManagementService.queryByUsername(username));
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 查询所有用户
     */
    @RequestMapping(value = "selectAllUser", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String selectAllUser() {
        try {
            return userManagementService.queryAllUser();
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 添加用户
     */
    @RequestMapping(value = "addUser", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String addUser(
            String username,
            String password,
            Integer rid
    ) {
        try {
            Role role = roleService.queryById(rid);
            if ("".equals(password)) {
                password = "123456";
            }
            password = MD5.MD5Encrypt(password);
            User user = new User(username, password, role);
            return userManagementService.addUser(user);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }

    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "delUser", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String delUser(
            Integer id
    ) {
        try {
            return userManagementService.delUser(id);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

    /**
     * 修改用户信息
     */
    @RequestMapping(value = "modifyUser", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    String modifyUser(
            Integer id,
            String username,
            String password,
            Integer rid
    ) {
        try {
            Role role = roleService.queryById(rid);
            if ("".equals(password)) {
                password = "123456";
            }
            password = MD5.MD5Encrypt(password);
            User user = new User(id, username, password, role);
            return userManagementService.modifyUser(user);
        } catch (MsgException e) {
            return e.toJson();
        } catch (UndeclaredThrowableException e) {
            Throwable undeclaredThrowable = e.getUndeclaredThrowable();
            if (undeclaredThrowable instanceof PermissionDeniedException) {

                return new MsgException(VerificationCode.NOT_PERMISSION, "没有该权限").toJson();
            } else {
                return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知权限错误").toJson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new MsgException(VerificationCode.UNKNOWN_ERROR, "未知错误").toJson();
        }
    }

}
